<template>
  <div>
    <div id="board-box">
      <div  style="padding: 0 10px;">
        <el-radio-group  size="small" v-model="projectsQuery.byType" @change="changeStaticMode()">
          <el-radio-button label="1" >日报</el-radio-button>
          <el-radio-button label="2" >周/月报</el-radio-button>
          <el-radio-button label="3" >年报</el-radio-button>
        </el-radio-group>
<!--        <a href="/#/wpb-log-detail?logId=1195163245697662978">日志详情测试</a>-->
        <div style="float:right; width:170px; height:40px;">
          <el-form label-width="70px">
            <el-form-item label="选择人员" prop="leader">
              <avatar-list ref="user" :eclipse="true" :clear="true" :maxNumber="100" @avatarChange="avatarChange" :disabledDingIds="this.unPermDingIds.split(',')" ></avatar-list>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div style="clear: both">
        <calendar ref="calendar2" v-if="multiAvatar && projectsQuery.byType==1">
          <template
            slot="dateCell"
            slot-scope="{user, data}">
            <div :class="'pj_flag '+ getFilterClass(data.day)" @click="showDailyLog(data.day, user.emplId)" style="cursor: pointer">
              <tip class="tip" v-for="item in getLogsByDateAndUser(data.day, user.emplId)" :key="item.logId" v-if="item.projectId>0" :disabled="!isPC()">
                <template slot="orin">
                  <i :class="'iconfont mi '+ item.icon" :style="'color:'+item.color" ></i>
                </template>
                <template slot="content">
                  <div>{{item.projectName}}：</div>
                  <div v-if="isFuture(data.day)" style="font-size: 10px">{{item.planStartTime}} 至 {{item.planEndTime}}</div>
                  <div>{{item.logContent}}</div>
                </template>
              </tip>
            </div>
          </template>
        </calendar>
      </div>

      <div  v-if="!multiAvatar" style="clear: both;">
        <div  v-if="projectsQuery.byType==1" style="position: relative">
          <el-calendar ref="calendar" v-model="currentDate" >   <!--:range="[thisWeekBegin(), thisWeekEnd()]" '2019-09-23', '2019-10-27'-->
            <template
              slot="dateCell"
              slot-scope="{date, data}">
              <div :class="'pj_flag '+ getFilterClass(data.day)" @click.stop="showDailyLog(data.day)">
                <div :class="getDayClass(data.day)">{{data.day.split('-').slice(2).join('.') }}</div>
                <tip class="tip" v-for="item in getLogsByDateAndUser(data.day)" :key="item.logId" v-if="item.projectId>0" :disabled="!isPC()">
                  <template slot="orin">
                    <i :class="'iconfont mi '+ item.icon" :style="'color:'+item.color" ></i>
                  </template>
                  <template slot="content">
                    <div>{{item.projectName}}：</div>
                    <div v-if="isFuture(data.day)" style="font-size: 10px">{{item.planStartTime}} 至 {{item.planEndTime}}</div>
                    <div>{{item.logContent}}</div>
                  </template>
                </tip>
              </div>
            </template>
          </el-calendar>
        </div>
      </div>

      <div  v-if="projectsQuery.byType==2" style="position: relative; min-height: 400px;">
        <monthly ref="monthly" >
          <template
            slot="dateCell"
            slot-scope="{user, data}">
            <div class="pj_flag" @click="showPhaseLog(data.day, user.emplId)">
              <div>{{data.day.split('-').slice(1).join('.') }}月</div>
              <tip class="tip" v-for="item in getPhasedLogs(data.day,user.emplId)" :key="item.logId" v-if="item.projectId<0 " :disabled="!isPC()">
                <template slot="orin">
                  <i :class="'iconfont mi '+item.icon" :style="'color:'+item.color" ></i>
                </template>
                <template slot="content">
                  <div>{{getPhasedDesc(item.projectId)}}</div>
                  <div>{{item.logTime}}</div>
                  <div>{{item.logContent}}</div>
                </template>
              </tip>
            </div>
          </template>
        </monthly>
      </div>

      <div v-if="projectsQuery.byType==3" style="width: 100%;text-align: center;">
        <div style="display: inline-block;">
          <chart v-if="pie.list.length>0" :ref="'chart'+index" v-for="(pie,index) in chartPie" :key="index" :chartData="pie" :index="index"></chart>
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="95%">
      <div>
        <div v-for="item in dialogData" style="padding-bottom: 20px;clear:both;">
          <div style="line-height: 14px; font-weight: bold">
            <i :class="'iconfont '+ item.icon" :style="'color:'+item.color"></i>
            {{item.projectName}} <br>
            <span v-if="item.projectId>1" style="font-size:10px;padding-left: 18px">
             {{item.planStartTime}} 至 {{item.planEndTime}}  <span v-if="item.projectId>1"> 状态：{{getDescription(item)}} </span>
            </span>
          </div>
          <div v-if="item.projectId>0" style="position: relative">
            <i class="el-icon-document"></i> 内容：
            <div v-html="item.logContent.replace(/\n/g,'<br/>')"> </div>
          </div>
          <div v-if="item.projectId<0" style="position: relative" v-html="item.logContent.replace(/\n/g,'<br/>')">
          </div>
          <img-viewer :data="item.attachmentList"></img-viewer>
          <comment v-if="item.projectId!=999" :userInfo="userInfo" :members="members" :log="item"></comment>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <ding-login ref="gate"></ding-login>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/index.css';
  import dingMixin from  '@/mixins/ding'
  import {dateUtil} from '@/utils/dateUtil'
  import AvatarList from '@/components/ding/avatar-list'
  import Comment from '@/components/ding/comment'
  import echarts from 'echarts'
  import calendar from '@/components/ding/calendar'
  import tip from '@/components/ding/tip'
  import DingLogin from '@/components/ding/ding-login'
  import Monthly from '@/components/ding/monthly'
  import Chart from '@/components/ding/chart'
  import ImgViewer from '@/components/common/img-viewer'

  export default {
    data () {
      return {
        currentDate: new Date(),
        dialogVisible: false,
        dialogTitle: '',
        dialogData:'',
        projectsQuery:{
          byType: 1,
          queryDepartmentId: '',
          queryDepartmentName:''
        },
        dataForm: {
          key: ''
        },
        logBoard:{
          logs:[],
          comments:[]
        },
        chartPie: null,
        members: [],
        multiAvatar: false,
        avatars:[],
        unFinishProjects: []
      }
    },
    mixins: [dingMixin],
    activated () {
      this.$refs.gate.login().then((flag)=>{
          this.run_dd_config();
          this.loadMembers().then(data=>this.members = data);
          if(this.$route.query.dingId){
            this.avatars = [{emplId:this.$route.query.dingId, name: this.$route.query.name}]
          }
          else{
            this.avatars =[{emplId:this.userInfo.dingId, name: this.userInfo.realName}]
          }
          this.$refs.user.bindData(this.avatars);
          this.getAllUnFinishProject()
          this.getLogBoards()
          this.changeStaticMode()
      })
    },
    created(){
      if(this.$route.query.projectId<0){
          this.projectsQuery.byType = 2
      }
    },
    computed:{

    },
    components:{
      AvatarList,Comment,calendar, tip, DingLogin, Monthly, Chart, ImgViewer
    },
    methods: {
      getComments(){
        return new Promise((resolve, reject)=> {
          this.$http({
            url: this.$http.adornUrl('/wpb/projectcomment/listComments'),
            method: 'post',
            data: this.$http.adornData({})
          }).then(({data}) => {
              if (data && data.code === 0) {
                 return resolve(data.data);
              } else {
                 return resolve([]);
              }
            }
          ).catch(error => {
            console.info(error)
          })
        });
      },
      avatarChange(dingIds){
        if(dingIds.length==0){
          return;
        }
        this.avatars = this.$refs.user.getAvatars();
        if(dingIds.length==1){
          this.multiAvatar = false
        }
        else{
          this.multiAvatar = true
          if(this.projectsQuery.byType==1){
            this.$nextTick(
              ()=>{
                this.$refs.calendar2.bindAvatars(this.avatars);
              }
            )
          }
        }
        if(this.projectsQuery.byType==2){
          this.$nextTick(
            ()=>{
              this.$refs.monthly.bindAvatars(this.avatars);
            }
          )
        }
        //console.log("avc:"+ JSON.stringify(this.avatars))
        if(this.projectsQuery.byType==3){
          this.getLogByYear();
        }
        else{
          this.getLogBoards()
        }
      },
      changeStaticMode(){
        if(this.projectsQuery.byType==3)
          this.getLogByYear();
        if(this.projectsQuery.byType==2){
          this.$nextTick(
            ()=>{
              this.$refs.monthly.bindAvatars(this.avatars);
            })
        }
        if(this.projectsQuery.byType==1){
           if(this.multiAvatar){
             this.$nextTick(
               ()=>{
                 this.$refs.calendar2.bindAvatars(this.avatars);
               }
             )
           }
        }
      },
      getAllUnFinishProject(){
        this.$http({
          url: this.$http.adornUrl('/wpb/projectbase/listAllProject'),
          method: 'post',
          params: this.$http.adornParams({flag: 1})
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.unFinishProjects = data.data;
            } else {
              this.unFinishProjects = [];
            }
          }
        ).catch(error=>{
          console.info(error)
        })
      },
      getLogsReq(){   //Daily phased
        return new Promise((resolve, reject)=>{
          this.$http({
            url: this.$http.adornUrl('/wpb/projectlog/getLogs'),
            method: 'post',
            data: this.$http.adornData({
              'memberId': this.getBoardDingId(),
              'logBeginTime': dateUtil.halfYearThisDay(),
              'logEndTime': dateUtil.thisDay(),
              'logType': 0
            })
          }).then(({data}) => {
              if (data && data.code === 0) {
                return resolve(data.data);
              } else {
                return resolve([]);
              }
            }
          ).catch(error=>{
            console.info(error)
          })
        })
      },
      getLogBoards(){
        this.getLogsReq().then((logs)=>{
           this.logBoard.logs = logs;
           this.getComments().then((comments)=>{
             this.logBoard.comments = comments
              for(let log of this.logBoard.logs){
                log.comment = this.getCommentsByLogId(log.id)
              }
           });
        });
      },
      getCommentsByLogId(logId){
        let res = this.logBoard.comments.filter(x=>{
          return x.logId == logId
        })
        return res;
      },
      getLogByYear(){
        this.$http({
          url: this.$http.adornUrl('/wpb/projectlog/getLogStatics'),
          method: 'post',
          data: this.$http.adornData({
            'memberId': this.$refs.user.getDingEmpIds().join(',') || this.$route.query.dingId || this.userInfo.dingId,
            'logBeginTime': this.thisYearBegin(),
            'logEndTime': this.thisYearEnd()
          })
        }).then(({data}) => {
            if (data && data.code === 0) {
              //this.$refs.chart1.initChartPie(data.data)
              this.chartPie = data.data
            } else {

            }
          }
        ).catch(error=>{
          console.info(error)
        })
      },

      getBoardDingId(){
        return this.$refs.user.getDingEmpIds().join(",") || this.$route.query.dingId || this.userInfo.dingId
      },
      getFutureLogs(date, dingId){
        let tmp = this.unFinishProjects.filter(x=>{
          //console.log(`,${x.members},${x.leader},`);
          //console.log(`,${dingId},`);
          return date>=x.planStartTime && date<= x.planEndTime && `,${x.members},${x.leader},`.indexOf(`,${dingId},`)>=0
        })
        let res = [];
        for(let p of tmp){
          let n =
          {
            "cc":p.cc,
            "color":p.color,
            "endTime":'',
            "flag":1,
            "icon": p.icon,
            "id":0,
            "logContent":"",
            "logTime": date,
            "leaderId": p.leader,
            "memberId": p.members,
            "memberName":"",
            "planEndTime": p.planEndTime,
            "planStartTime": p.planStartTime,
            "projectId": p.id,
            "projectName": p.name,
            "status": "",
          }
          res.push(n);
        }
        return res;
      },
      isToday(date){
        return dateUtil.thisDay() == date;
      },
      isFuture(date){
        let today = dateUtil.thisDay();
        return date > today
      },
      getPhasedLogs(date, dingId){
        if(!dingId){
          dingId = this.getBoardDingId()
        }
        let res = this.logBoard.logs.filter(x=>{
          return x.logTime.indexOf(date)==0 && x.memberId ==dingId && x.projectId<0
        })
        console.log('phased:'+ JSON.stringify(res))
        return res;
      },
      getLogsByDateAndUser(date, dingId){
        if(!dingId){
          dingId = this.getBoardDingId()
        }
        if(this.isFuture(date)){
          /*if(dateUtil.getWeek(date)=='周日'){return;}*/
          return this.getFutureLogs(date, dingId);
        }
        else{
          let res = this.logBoard.logs.filter(x=>{
            return x.logTime == date && x.memberId ==dingId && x.projectId>0
          })
          return res;
        }
      },
      getDescription(logItem){
        if(logItem.status==1){
          return "进行中";
        }
        else if(logItem.status==2){
          return "已完成";
        }
        else if(logItem.status==3){
          return "已逾期";
        }
        else if(logItem.status==4){
          return "逾期已完成";
        }
      },
      getPhasedDesc(prjId){
        if(prjId==-4){
          return '月报'
        }
        else if(prjId==-3){
          return '半月报'
        }
        else if(prjId==-2){
          return '周报'
        }
        return '总结'
      },
      thisYearBegin(){
        return dateUtil.thisYearBegin();
      },
      thisYearEnd(){
        return dateUtil.thisYearEnd();
      },
      showDailyLog(date, dingId){
        if(this.isFuture(date)){
          return;
        }
        if(!dingId){
          dingId = this.getBoardDingId()
        }

        let t = this.getLogsByDateAndUser(date, dingId)
        //console.log(JSON.stringify(t));
        if(t.length>0){
          this.dialogVisible = true
          this.dialogTitle = `${t[0].logTimeStr} ${t[0].memberName} ${t[0].position}`
          this.dialogData = t;
        }
      },
      showPhaseLog(date, dingId){
        if(!dingId){
          dingId = this.getBoardDingId()
        }

        let t = this.getPhasedLogs(date, dingId)
        //console.log(JSON.stringify(t));
        if(t.length>0){
          this.dialogVisible = true
          this.dialogTitle = `${date} ${t[0].memberName} ${t[0].position}`
          this.dialogData = t;
        }
      },
      getDayClass(date){
        let tmp= new Date(Date.parse(date));
        if(this.currentDate.getMonth()!= tmp.getMonth() || this.currentDate.getFullYear()!=tmp.getFullYear()){
          return "gray";
        }
        return "";
      },
      getFilterClass(date){
        if(this.isToday(date)){
          return 'today'
        }
        else if(this.isFuture(date)){
          return 'future'
        }
        else{
          return 'ago'
        }
      },
    },
    watch:{
      'projectsQuery.byType'(newVal,oldVal){

      }
    }
  }
</script>
<style>
  #board-box{
    padding: 15px 0;
    margin-bottom: 40px;
  }

  #board-box .el-calendar__body{
    padding: 8px;
  }

  .el-calendar-table td.is-selected{
    background: rgb(236, 245, 255);
  }

   .el-dialog__body{
    line-height: 25px;
    padding: 15px;
  }

</style>
<style lang="scss" scoped>

  .avatar{
    width: 36px;
    height: auto;
    margin-right: 0px;
    border-radius: 100%;
    vertical-align: middle;
  }

  .foot div{
    float:left;
    height:50px;
    width:33%;
    padding:5px;
    text-align: center;
  }

  .colorBoard{
    position: fixed;
    top: 50px;
    left:0px;
    padding:5px;
    background: white;
    width:100%;
  }

  .pj_flag{
    width:100%;
    height:100%;
  }

  i:before{
    font-size: 15px;
  }

  .gray{
    color:#c0c4cc;
  }

  .mi{
    padding: 3px;
    margin-left: 3px;
  }

  .tip{
    width:28px; height:28px; float:left; color:#606266;
  }

  .feedback{
    position: relative;
    right:0px;
  }

  .delc{
    cursor: pointer; margin-left: 15px; color:gray; font-size: 10px;
  }

  .future{
    cursor: default;
    i{
      -webkit-filter: opacity(30%); /* Chrome, Safari, Opera */
      filter: opacity(30%);
    }
  }

  .today{
    i{
      -webkit-filter: drop-shadow(1px 1px 1px ); /* Chrome, Safari, Opera */
      filter: drop-shadow(1px 1px 1px );
    }

  }

  .ago{
    i{
      -webkit-filter: drop-shadow(1px 1px 1px ); /* Chrome, Safari, Opera */
      filter: drop-shadow(1px 1px 1px );
    }
  }

</style>

<!--          <div style="position: absolute; right:20px; top:12px; z-index: 2">
            <div class="el-button-group">
              <button type="button" @click="preMonth()" class="el-button el-button&#45;&#45;plain el-button&#45;&#45;mini">&lt;!&ndash;&ndash;&gt;&lt;!&ndash;&ndash;&gt;<span>
              上个月
            </span></button>
              <button type="button" @click="curMonth()" class="el-button el-button&#45;&#45;plain el-button&#45;&#45;mini">&lt;!&ndash;&ndash;&gt;&lt;!&ndash;&ndash;&gt;<span>
              今天
            </span></button>
              <button type="button" @click="nxtMonth()" class="el-button el-button&#45;&#45;plain el-button&#45;&#45;mini">&lt;!&ndash;&ndash;&gt;&lt;!&ndash;&ndash;&gt;<span>
              下个月
            </span></button>
            </div>


                  preMonth(){
                    this.$refs.calendar.selectDate('prev-month');
                  },
                  nxtMonth(){
                    this.$refs.calendar.selectDate('next-month');
                    if(this.currentDate.getMonth() > (new Date()).getMonth()){
                      return
                    }
                  },
                  curMonth(){
                    this.$refs.calendar.selectDate('today');
                  }
          </div>
      getLogBoards(){
this.$http({
url: this.$http.adornUrl('/wpb/projectlog/getLogs'),
method: 'post',
data: this.$http.adornData({
/!*            'page': 1,
'limit': 1000,*!/
'memberId': this.getBoardDingId(),
'logBeginTime': dateUtil.halfYearThisDay(),
'logEndTime': dateUtil.thisDay()
})
}).then(({data}) => {
if (data && data.code === 0) {
this.logBoard.logs = data.data;
} else {
this.logBoard.logs = [];
}
}
).catch(error=>{
console.info(error)
})
},-->
